const sender = {
  pvUrl: '/api/collections/pv',
  eventUrl: '/api/collections/events',
}

sender.sendPv = data => {
  localStorage.setItem('pair_4th_data', JSON.stringify(data))
  _post(sender.pvUrl, data)
}

sender.sendListenEvent = data => {
  _post(sender.eventUrl, data)
}

mergeUser = (data) => {
  const userJson = localStorage.getItem('pair_4th_user')
  if (userJson) {
    const {userId} = JSON.parse(userJson)
    return {...data, userId}
  }
  return data
}
const _post = (url, data, callback) => {
  data = mergeUser(data)
  const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  xhr.open('POST', url);
  xhr.onreadystatechange = function () {
    if (xhr.readyState > 3 && xhr.status === 200) {
      callback && callback(xhr.responseText);
    }
  };
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
  xhr.send(JSON.stringify(data));
  return xhr;
}